<template>
  <div class="import-container p-4">
    <el-card class="mb-4">
      <el-form :inline="true" label-width="100px">
        <el-form-item label="选择城市：">
          <el-select v-model="selectedCity">
            <el-option label="厦门" value="厦门" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="上传Excel：">
          <el-upload
            class="upload-demo"
            accept=".xlsx,.xls"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleExcelUpload"
          >
            <el-button type="primary">选择文件</el-button>
            
          </el-upload>
        </el-form-item>
        <el-form-item>
            <el-button 
                type="primary" 
                @click="handleSubmit" 
                :loading="uploading"
                :disabled="!tableData.length"
            >确认上传</el-button>
        </el-form-item>
        <el-form-item>
            <el-button 
              :type="canDownload ? 'success' : 'info'" 
              @click="handleDownload" 
              :disabled="!canDownload"
            >
              {{ downloadButtonText }}
            </el-button>
        </el-form-item> 
      </el-form>
    </el-card>

    <el-card>
      <el-table :data="paginatedData" border>
        <template v-for="(value, key) in (tableData[0] || {})" :key="key">
          <el-table-column :prop="key" :label="key" />
        </template>
      </el-table>
      <div v-if="tableData.length > 0" class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="tableData.length"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import * as XLSX from "xlsx";
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
import { queryBatchStatus,createBatch,queryBatchDetail } from '@/api/supervise/import'

const tableData = ref<Array<Record<string, unknown>>>([])
const selectedCity = ref('厦门')

// 获取路由实例
const route = useRoute()
const router = useRouter()

const batchId = ref(route.query.batch_no as string || '')
const uploading = ref(false)
const canDownload = ref(false)
const pollingTimer = ref<number | null>(null)
const currentPage = ref(1)
const pageSize = ref(10)

// 下载按钮文字
const downloadButtonText = computed(() => {
  if(!batchId.value && !canDownload.value){
    return '等待上传'
  }
  if (batchId.value && !canDownload.value) {
    return '上传处理中'
  }
  return '下载结果'
});

// 轮询状态
const pollStatus = async () => {
  if(!batchId.value){
    ElMessage.warning('请先上传文件')
    return
  }
  try {
    const response = await queryBatchStatus({
      batch_no: batchId.value
    })
    
    if ([1,2].includes(response.status)) {
      if(response.status === 2){
        ElMessage.error('查询失败')
      }
      if(response.status === 1){
        canDownload.value = true
        ElMessage.success('上传成功')
      }
      if (pollingTimer.value) {
        clearInterval(pollingTimer.value)
        pollingTimer.value = null
      }
    }
  } catch (error) {
    console.error('状态查询失败:', error)
  }
}

// 组件加载时检查是否有未完成的任务
onMounted(() => {
  if (batchId.value) {
    pollingTimer.value = setInterval(pollStatus, 3000) as unknown as number
  }
})

// 计算分页后的数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return tableData.value.slice(start, end)
})

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 修改handleExcelUpload函数，在设置tableData后重置分页
const handleExcelUpload: UploadProps['onChange'] = (uploadFile) => {
  const file = uploadFile.raw
  if (!file) return
  batchId.value=""
  const reader = new FileReader()
  reader.onload = (e) => {
    const data = e.target?.result
    if (!data) return
    
    try {
      const workbook = XLSX.read(data, { type: 'binary' })
      const firstSheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[firstSheetName]
      const results = XLSX.utils.sheet_to_json(worksheet)
      
      // 检查数据行数
      if (results.length > 1000) {
        ElMessage.warning(`Excel文件数据共${results.length}行，超过1000行限制，请减少数据量后重试`)
        return
      }
      
      tableData.value = results as Array<Record<string, unknown>>
      currentPage.value = 1 // 重置页码
    } catch (error) {
      console.error('Excel解析错误:', error)
      ElMessage.error('Excel文件解析失败，请检查文件格式')
    }
  }
  
  reader.onerror = () => {
    ElMessage.error('文件读取失败')
  }
  
  reader.readAsBinaryString(file)
}

const handleSubmit = async () => {
  if (!tableData.value.length) {
    ElMessage.warning('请先选择并上传Excel文件')
    return
  }

  try {
    uploading.value = true
    canDownload.value = false
    const params = {
      city: selectedCity.value,
      items: tableData.value
    }
    const response = await createBatch(params)
    ElMessage.success('数据上传成功')
    batchId.value = response.batch_no
    
    // 修改 URL 参数
    router.replace({
      query: { ...route.query, batch_no: response.batch_no }
    })
  
    // 开始轮询状态
    if (pollingTimer.value) {
      clearInterval(pollingTimer.value)
    }
    pollingTimer.value = setInterval(pollStatus, 3000) as unknown as number
    
    // 清空数据
    tableData.value = []
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('数据上传失败，请重试')
  } finally {
    uploading.value = false
  }
}

// 字段映射配置
const fieldMapping = {
  id_card: '身份证号',
  plate_number: '车牌号',
  license_name: '运输证名称',
  vehicle_owner: '车辆所有人',
  vehicle_create_time: '车辆发证日期',
  vehicle_validity_period: '车辆有效期',
  vehicle_platform: '车辆平台',
  vehicle_status: '车辆状态',
  driver_cert_type: '驾驶员证件类型',
  driver_create_time: '驾驶员发证日期',
  driver_validity_period: '驾驶员有效期',
  driver_status: '驾驶员状态'
}

const handleDownload = async () => {
  try {
    const response = await queryBatchDetail({
      batch_no: batchId.value,
    })
    
    if (!response || !Array.isArray(response)) {
      throw new Error('返回数据格式错误')
    }
    
    // 转换数据，将英文字段名替换为中文
    const mappedData = response.map((item: Record<string, any>) => {
      const mappedItem: Record<string, any> = {}
      for (const [key, value] of Object.entries(item)) {
        mappedItem[fieldMapping[key as keyof typeof fieldMapping] || key] = value
      }
      return mappedItem
    })
    
    // 创建工作簿
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.json_to_sheet(mappedData)
    XLSX.utils.book_append_sheet(wb, ws, '数据')
    
    // 导出Excel文件
    XLSX.writeFile(wb, `导入结果_${new Date().getTime()}.xlsx`)

  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请重试')
  }
}

// 组件卸载时清除定时器
onUnmounted(() => {
  canDownload.value = false
  uploading.value = false
  if (pollingTimer.value) {
    clearInterval(pollingTimer.value)
    pollingTimer.value = null
  }
})
</script>

<style scoped>
:deep(.el-form--inline .el-form-item) {
  margin-right: 12px;
}
.import-container {
  min-height: 100%;
}
</style>